import axios from 'axios';
import { message } from 'antd';

const instance = axios.create({
  baseURL: 'http://81.70.93.163:8000/api/',
  timeout: 6000,
});

//请求拦截处理
instance.interceptors.request.use(
  function (config) {
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  },
);

instance.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response;
  },
  function (error) {
    // 对响应错误做点什么
    if (error && error.response) {
      const errorText =
        typeof error.response.data.message === 'string'
          ? error.response.data.message
          : Object.values(error.response.data.message)[0];
      console.log('errorText', errorText);
      message.error(errorText);
    }
    return Promise.reject(error);
  },
);

const post = (
  api: any,
  data: any,
  headers = { 'Content-Type': 'application/json;charset=utf-8' },
) => {
  return new Promise((resolve, reject) => {
    instance
      .post(api, data, { headers })
      .then((res) => {
        resolve(res);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

const get = (api: any, params = {}, headers = {}) => {
  return new Promise((resolve, reject) => {
    instance
      .get(api, { params, headers })
      .then((res) => {
        resolve(res);
      })
      .catch((error) => {
        reject(error);
      });
  });
};
// 导出，供各页面调用
export default { post, get };
